import json
import os


if __name__ == "__main__":
    current_path = os.path.dirname(__file__)
    new_jsonfile = open(current_path + '/bulk_data.json', 'w', encoding='UTF-8')
    # w打开一个文件只用于写入
    # 如果该文件已存在则打开文件，并从开头开始编辑，即原有内容会被删除
    # 如果该文件不存在，创建新文件

    with open('/Users/zhuangshilin/Documents/碳数据文件/files_info.json', 'r', encoding='utf8') as fp:
        json_data = json.load(fp)
        # json_data是list
        # json_data['RECORDS'][i]是dict
        id_num = 1
        for i in range(0, len(json_data['RECORDS'])):
            # 添加index行
            new_data = {}
            new_data['index'] = {}
            new_data['index']['_index'] = "records"
            new_data['index']['_type'] = "doc"
            new_data['index']['_id'] = str(id_num)
            id_num = id_num + 1
            temp = json.dumps(new_data).encode("utf-8").decode('unicode_escape')
            new_jsonfile.write(temp)
            new_jsonfile.write('\n')
            # 原json对象处理为1行
            old_data = {}
            old_data['id'] = json_data['RECORDS'][i]['id']
            old_data['url'] = json_data['RECORDS'][i]['url']
            old_data['label'] = json_data['RECORDS'][i]['label']
            old_data['name'] = json_data['RECORDS'][i]['name']
            old_data['rank'] = json_data['RECORDS'][i]['rank']
            temp = json.dumps(old_data).encode("utf-8").decode('unicode_escape')
            new_jsonfile.write(temp)
            new_jsonfile.write('\n')
        print("写入成功，生成bulk_data.json")

    new_jsonfile.close()
